<template>
    <van-popup position="bottom" round v-model:show="show" closeable>
        <div class="add-wrap">
            <div class="head">
                <div class="left">
                    <span @click="changeType('expense')" :class="{ 'active': payType === 'expense' }">支出</span>
                    <span @click="changeType('income')" :class="{ 'active': payType === 'income' }">收入</span>
                </div>
                <div class="right" @click="showTime = true">
                    <span>{{ date[1] }}月{{ date[2] }}日 <van-icon style="transform: rotate(90deg);" name="play" /></span>
                </div>
            </div>
            <div class="money">
                <span class="icon">￥</span>
                <span class="amount">{{ amount }}</span>
            </div>
            <div class="type-wrap">
                <div class="expense grid" v-if="payType === 'expense'">
                    <div v-for="item in expense" class="item" :key="item.id" @click="selectType(item)">
                        <i class="iconfont"
                            :class="[icons[item.name], currentType.id === item.id ? 'isActive' : '']"></i>
                        <p>{{ item.name }}</p>
                    </div>
                </div>
                <div class="income grid" v-else>
                    <div v-for="item in income" class="item" :key="item.id" @click="selectType(item)">
                        <i class="iconfont"
                            :class="[icons[item.name], currentType.id === item.id ? 'isActive2' : '']"></i>
                        <p>{{ item.name }}</p>
                    </div>
                </div>
            </div>
            <div class="remark">
                <input v-model="remark" type="text" placeholder="添加备注">
            </div>
            <div class="keyboard">
                <van-number-keyboard show theme="custom" extra-key="." close-button-text="确定" @input="onInput"
                    @delete="onDelete" @close="addBill"
                    :style="{ '--van-number-keyboard-button-background': '#37a762' }" />
            </div>
        </div>
    </van-popup>

    <van-popup position="bottom" round v-model:show="showTime">
        <van-date-picker v-model="currentDate" title="选择日期" :min-date="new Date(2020, 0, 1)" :max-date="new Date()"
            @cancel="showTime = false" @confirm="selectTime" />
    </van-popup>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import axios from '@/api/index.js'
import icons from '@/utils/icons.js'
import formatteDate from '@/utils/date.js'
import { showToast } from 'vant';
import { showSuccessToast } from 'vant';

const props = defineProps({
    billDetail: {
        type: Object,
        default: () => ({})
    }
})

watch(() => props.billDetail.pay_type, (newVal) => {
    if (newVal === 2) {
        payType.value = 'income'
    } else {
        payType.value = 'expense'
    }
    date.value = formatteDate(new Date(Number(props.billDetail.date)))
    currentType.value = {
        id: props.billDetail.type_id,
        name: props.billDetail.type_name
    }
    amount.value = props.billDetail.amount
    remark.value = props.billDetail.remark
    id.value = props.billDetail.id
})


const show = ref(false)
const showTime = ref(false)
const expense = ref([])
const income = ref([])
const payType = ref('expense')  // 支出收入
const currentDate = ref(formatteDate(new Date()))
const date = ref(formatteDate(new Date())) // 确定的日期 
const currentType = ref({})
const remark = ref('')
const amount = ref('')
const emits = defineEmits(['queryAccount'])
const id = ref('')

onMounted(async () => {
    const { data } = await axios.get('/api/type/list')
    // console.log(data);
    expense.value = data.list.filter((item) => {
        return item.type === '1'
    })
    income.value = data.list.filter((item) => {
        return item.type === '2'
    })
    currentType.value = expense.value[0]
    if (props.billDetail.type_id) {
        currentType.value = {
            id: props.billDetail.type_id,
            name: props.billDetail.type_name
        }
    }
})

const changeType = (type) => {
    payType.value = type
}

const selectTime = () => {
    date.value = currentDate.value
    showTime.value = false
}

const selectType = (item) => {
    //console.log(item);
    currentType.value = item
}

const onInput = (val) => {
    if (val === '.' && amount.value.includes('.')) return
    if (amount.value && amount.value.includes('.') && amount.value.split('.')[1].length >= 2) return
    amount.value += val
}

const onDelete = () => {
    amount.value = amount.value.slice(0, -1)
}

const addBill = async () => {
    if (Number.isNaN(Number(amount.value)) || amount.value === '') {
        showToast('请输入正确的金额')
        return;
    }
    // 需要给后端的参数
    const params = {
        amount: Number(amount.value).toFixed(2),
        type_id: currentType.value.id,
        type_name: currentType.value.name,
        date: new Date(date.value.join('-')).getTime(),
        pay_type: payType.value === 'expense' ? 1 : 2,
        remark: remark.value,
        id: id.value
    }
    if (!id.value) {
        const res = await axios.post(`/api/bill/add`, params)
        show.value = false
        // 促使父组件重新请求数据
        emits('queryAccount')
        // 清空数据
        currentType.value = expense.value[0]
        amount.value = ''
        remark.value = ''
        payType.value = 'expense'
        date.value = formatteDate(new Date())
    } else {
        const res = await axios.post(`/api/bill/update`, params)
        show.value = false
        showSuccessToast('编辑成功！')
        emits('queryAccount')
        // // 清空数据
        // currentType.value = expense.value[0]
        // amount.value = ''
        // remark.value = ''
        // payType.value = 'expense'
        // date.value = formatteDate(new Date())
    }
}

defineExpose({
    show
})
</script>

<style lang="less" scoped>
.add-wrap {
    padding: 60px 20px 0;

    .head {
        display: flex;
        justify-content: space-between;

        .active {
            background-color: rgb(230, 247, 238);
            color: #37a762;
        }

        span {
            padding: 5px 10px;
            background-color: rgb(245, 245, 245);
            color: #666;
            margin-right: 10px;
            border-radius: 4px;
        }
    }

    .money {
        padding: 30px 0;
        font-size: 30px;
        font-weight: bold;
        border-bottom: 1px solid #f1f1f1;

        .amount {
            margin-left: 10px;
        }
    }

    .type-wrap {
        margin: 10px 0;
        height: 110px;
        overflow-y: scroll;

        .grid {
            display: grid;
            grid-template-columns: repeat(6, 1fr);
            text-align: center;
            grid-column-gap: 20px;
            grid-row-gap: 10px;

            .iconfont {
                display: inline-block;
                width: 30px;
                height: 30px;
                line-height: 30px;
                border-radius: 50%;
                text-align: center;
                //background-color: #37a762;
                background-color: #eee;
                color: #999;
                margin-bottom: 5px;

                &.isActive {
                    background-color: #37a762;
                    color: #fff
                }

                &.isActive2 {
                    background-color: #F2B63B;
                    color: #fff
                }
            }
        }
    }

    .remark {
        margin: 15px 0;

        input {
            width: 100%;
            padding: 5px 0;
            border-radius: 4px;
            border: none;
            box-sizing: border-box;
            font-size: 16px;
        }
    }

    .keyboard {
        height: 244px;
    }
}
</style>